using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsLive.Id.Client;
using System.Threading;

namespace IReaper.Command
{
    class OpenAuthenticatedRegistrationCommand:CommandBase
    {
        public override void CommandBody(object sender, params object[] paras)
        {
            //the parameter is the event id
            if (paras.Length < 1)
                return;
            string eventID = paras[0] as string;
            if (eventID == null)
                return;
            //open form in proper syncontext
            if (SynchronizationContext.Current is System.Windows.Forms.WindowsFormsSynchronizationContext)
            {
                this.Open(eventID);
            }
            else
            {
                FileData.CourseFileData.async.Post(Open, eventID);
            }
        }

        private void Open(object EventID)
        {
            if (EventID == null)
                return;
            Identity oID = WWE.WWEManager.oID;
            string eventID = EventID as string;

            if (oID.IsAuthenticated || oID.Authenticate())
            {
                string outUrl = null, postData = null;
                oID.GetNavigationData("http://msevents.microsoft.com/CUI/Register.aspx?EventID=" + eventID, "lbi", ref outUrl, ref postData);
                Browser.iReaperBrowserForm form = new IReaper.Browser.iReaperBrowserForm();
                byte[] postByte = System.Text.Encoding.ASCII.GetBytes(postData);
                form.NavigateWithPostedAuthenInfo(outUrl, postByte);
                form.Show();
            }
        }

        public override CommandFamily Family
        {
            get { return CommandFamily.Command_OpenAuthenBrowser; }
        }
    }
}
